package com.min.log

import javassist.ClassPool
import org.gradle.api.Project

class InjectClient implements Client{

    private static final String ACTIVITY = "activity"
    private static final String ACTIVITY_INNER = "activity\$"
    private static final String PRESENTER = "presenter"
    private static final String COMPONENT = "component"
    private static final String MEMBERS_INJECT = "membersinjector"
    private static final String SCOPE = "scope"
    private static final String CLICK = "click"
    private static final String LISTENER = "listener"

    void inject(String path, Project project) {
        ClassPool pool = ClassPool.getDefault()
        pool.appendClassPath(path)

        //project.android.bootClasspath 加入android.jar，否则找不到android相关的所有类
        pool.appendClassPath(project.android.bootClasspath[0].toString())

        File classes = new File(path)
        realInject(classes, path)
    }

    private void realInject(File root, String path) {
        if (root.exists()) {
            if (root.isDirectory()) {
                root.eachFile {
                    file ->
                        if (file.isDirectory()) {
                            //递归
                            realInject(file, path)
                            //如果是具体的class文件
                        } else {
                            def fileName = file.name
                            //将所有的字符转为小写，便于匹配关键词
                            def name = fileName.toLowerCase()
                            println(name)
                            //排除特殊类，由dagger生成的类或者匿名内部类
                            if (name.contains(ACTIVITY) && !name.contains(COMPONENT) && !name.contains(MEMBERS_INJECT)
                                    && !name.contains(SCOPE) && !name.contains(ACTIVITY_INNER)) {
                                println(name + "已处理")
                                ActivityInject.injectDir(file, path)
                                //如果是activity或者presenter的内部类，或者包含click和listener的类，尝试解析当前的类是否包含click方法
                            } else if ((name.contains(ACTIVITY) || name.contains(PRESENTER))
                                    && (name.contains(ACTIVITY_INNER) || (name.contains(CLICK) && name.contains(LISTENER)))) {
                                println(name + "已处理")
                                ClickInject.inject(file, path)
                            }
                        }
                }
            }
        }
    }
}